package com.peng.leetcode.tree;

/**
 * SumOfLeftLeaves
 * 404. 左叶子之和
 * https://leetcode.cn/problems/sum-of-left-leaves/
 * <p>
 * Created on 2022/11/27
 *
 * @author lupeng
 */
public class SumOfLeftLeaves {

    int ans = 0;

    public int sumOfLeftLeaves(TreeNode root) {
        dfs(root);
        return ans;
    }

    private void dfs(TreeNode r) {
        if (r == null) {
            return;
        }
        if (r.left != null) {
            if (isLeaf(r.left)) {
                ans += r.left.val;
            }
            dfs(r.left);
        }
        if (r.right != null) {
            dfs(r.right);
        }
    }

    private boolean isLeaf(TreeNode n) {
        return n.left == null && n.right == null;
    }

}
